package com.wang.web.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;

import com.wang.web.forms.SignupForm;

@Controller("SignupController")
@RequestMapping("/signup")
public class SignupController
{
	@Autowired
	private SignInAdapter signInAdapter;
	
	@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator((org.springframework.validation.Validator) new Validator());
    }
	
	@RequestMapping(method=RequestMethod.GET)
	public String signup(WebRequest request, ModelMap model)
	{
	    Connection<?> connection = ProviderSignInUtils.getConnection(request);
	    SignupForm signupForm = null;
	    if (connection != null) {
	    	signupForm = new SignupForm(connection.fetchUserProfile());
	    } else {
	    	signupForm = new SignupForm();
	    }
	    model.addAttribute("signupForm", signupForm);
	    return "signup";
	}
	
	@RequestMapping(method = RequestMethod.POST, params="signup")
	public String signup(@Valid SignupForm form, WebRequest request, ModelMap model)
	{
		// Mockup user sign in
		Connection<?> connection = ProviderSignInUtils.getConnection(request);
	    String username = connection.fetchUserProfile().getUsername();
		signInAdapter.signIn(username, connection, (NativeWebRequest) request);

		return skipSignup(request, model);
	}
	
	@RequestMapping(method = RequestMethod.POST, params="skipSignup")
	public String skipSignup(WebRequest request, ModelMap model)
	{
	    Connection<?> connection = ProviderSignInUtils.getConnection(request);
	    String username = connection.fetchUserProfile().getUsername();
	    
	    // Save connection to repository
	    ProviderSignInUtils.handlePostSignUp(username, request);
	    
	    return "redirect:/";
	}
}

class Validator implements org.springframework.validation.Validator
{
	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return true;
	}

	public void validate(Object arg0, Errors arg1) {
		// TODO Auto-generated method stub
	}
}
